package com.example.shop_2210.frag

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.base.mvvm.BaseFragment
import com.example.shop_2210.R
import com.example.shop_2210.adapter.OneAdapter
import com.example.shop_2210.adapter.TwoAdapter
import com.example.shop_2210.databinding.FragmentCategoryBinding
import com.example.shop_2210.fragviewModel.CategoryViewModel

class CategoryFragment : BaseFragment<FragmentCategoryBinding,CategoryViewModel>() {
    lateinit var oneAdapter: OneAdapter
    lateinit var twoAdapter: TwoAdapter

    var isClick = false;//是否是点击状态，判断二级分类的滑动是否影响一级分类
    override fun initData() {
        viewModel.success.observe(this){
            if(it.code==200){
                oneAdapter.data.clear()
                oneAdapter.data.addAll(it.data)
                oneAdapter.notifyDataSetChanged()

                twoAdapter.data.clear()
                twoAdapter.data.addAll(it.data)
                twoAdapter.notifyDataSetChanged()
            }
        }
    }

    override fun initView() {
        oneAdapter = OneAdapter()
        binding.rvOne.adapter = oneAdapter
        binding.rvOne.layoutManager = LinearLayoutManager(context)

        twoAdapter = TwoAdapter()
        binding.rvTwo.adapter = twoAdapter
        val layoutManager = LinearLayoutManager(context)//将二级分类的布局管理器提成变量，为了后续可以改变位置
        binding.rvTwo.layoutManager = layoutManager
        viewModel.category()//请求一级二级分类数据

        //点击一级分类，二级分类数据滑动，将对应内容置顶
        oneAdapter.setOnItemClickListener { adapter, view, position ->
            oneAdapter.setId(oneAdapter.data[position].id)//设置选中背景色
            isClick = true//二级滑动不影响一级数据
            layoutManager.scrollToPositionWithOffset(position,0)
            isClick = false//二级滑动结束后，将状态改为不是点击

        }

        binding.rvTwo.addOnScrollListener(object :RecyclerView.OnScrollListener(){
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                if(isClick){//如果是点击事件引起滑动，那么直接退出
                    return
                }
                changeId()//改变一级分类的选中值
            }
            private fun changeId() {
                //获取第一个可见的item下标
                val itemPosition = layoutManager.findFirstVisibleItemPosition()
                if(oneAdapter.selectedId!=twoAdapter.data[itemPosition].id){//是否和一级分类中的默认选中的id相同
                    oneAdapter.setId(twoAdapter.data[itemPosition].id)
                    binding.rvOne.scrollToPosition(itemPosition)
                }
            }
        })
    }

    override fun getViewModel(): Class<CategoryViewModel> = CategoryViewModel::class.java

    override fun getLayout(): Int  = R.layout.fragment_category

}